#include <stdint.h>  // 替换为标准头文件
#include "led.h"
#include "systick_timer.h"
#include "usart.h"
#include <libopencm3/stm32/rcc.h>
#include <libopencm3/stm32/gpio.h>
#include <libopencm3/stm32/usart.h>
#include <libopencm3/cm3/nvic.h>


int main(void) {
    // 硬件初始化
    led_gpio_setup();
// 在main函数开始处添加系统时钟配置
// 配置系统时钟为 168MHz (典型值)
    rcc_clock_setup_pll(&rcc_hse_8mhz_3v3[RCC_CLOCK_3V3_168MHZ]);

// 现在可以安全地初始化 SysTick
    systick_timer_init(1000); // 1000ms 周期


    uint8_t led_state = 0;

     usart_auto_init(USART1);
    usart_send_string(USART1, "USART1 auto initialized, using default settings.\r\n");
    // 启用非阻塞接收
    usart_enable_nonblocking(USART1);

    // 手动初始化USART2，自定义参数
    UsartParameters custom_params = {
            .baudrate =115200,
            .databits = 8,
            .stopbits = USART_STOPBITS_1,
            .parity = USART_PARITY_NONE,
            .flow_control = USART_FLOWCONTROL_NONE,
            .mode = USART_MODE_TX_RX
    };
    usart_manual_init(USART2, &custom_params);
    usart_enable_nonblocking(USART2);
    usart_send_string(USART2, "USART2 manually initialized, using custom settings.\r\n");

    uint8_t led_switched = 0;
    while (1) {
        // 非阻塞接收
        // 处理USART1输入
        if (usart_has_line(USART1)) {
            const char* line = usart_get_line(USART1);
            usart_send_string(USART1, "USART1 received: ");
            usart_send_string(USART1, line);
            usart_send_string(USART1, "\r\n");
        }

        // 处理USART2输入
        if (usart_has_line(USART2)) {
            const char* line = usart_get_line(USART2);
            usart_send_string(USART2, "USART2 received: ");
            usart_send_string(USART2, line);
            usart_send_string(USART2, "\r\n");
        }

        uint64_t current_count = systick_timer_get_count();
        if (current_count % 1000 == 0 && current_count > 0) {
            if (!led_switched) {
                led_state = !led_state;
                led_update_state(led_state);
                led_switched = 1;
            }
        } else {
            led_switched = 0;
        }
    }

    return 0;
}